var fs = require('fs')
var path = require("path")
const chokidar = require('chokidar')
/*const js_reg = new RegExp(/<script(?:.*?)src=(.+?)>(?:[\n\r\s]*?)(?:<\/script>)*!/gm);//获取js
const css_reg = new RegExp(/<link(?:.*?)href=(.+?)>/gm);//获取css
const str_reg = /^["|'](.*)["|']$/g;//去除多引号*/
const configPath = './public/apps.config.json'
fs.writeFileSync(configPath, JSON.stringify({}, null, "\t"))
//主程序入口
/*const programEntryReg = RegExp(/\/(app|main)(?:.*?).js/)
const PORT = process.env.PORT || '3000'
const server = "localhost:" +PORT //服务器地址拼接后http://localhost:3000/模块名/static/js/*/




//模块添加
function fileUpdate(src, moduleName) {
    let configs = require(configPath);
    try {
        let moduleJson = JSON.parse(fs.readFileSync(src, 'utf-8'));
        let {manifest = {}, metadata = {}, app = {}} = moduleJson || {}
        manifest = getUrl(moduleName, manifest.js)
        let resourceEntryUrl = getUrl(moduleName, app.js)
        //删除已赋值
        delete moduleJson.manifest
        delete moduleJson.metadata
        if (app[js]) delete moduleJson.app[js]
        //添加css和js
        let scriptList = [], cssList = []
        Object.keys(moduleJson).forEach(v => {
            let {css, js} = moduleJson[v]
            css = getUrl(moduleName, css)
            js = getUrl(moduleName, js)
            css && cssList.push(css)
            js && scriptList.push(js)
        })

        configs[moduleName] = {
            manifest, ...metadata, resourceEntryUrl, scriptList, cssList
        }
        if (!resourceEntryUrl) {
            console.log(moduleName + '模块resourceEntryUrl入口文件不能为空，则index.json里的app.js')
            delete configs[moduleName]
        }
        fs.writeFileSync(configPath, JSON.stringify(configs, null, "\t"))

        if (resourceEntryUrl) console.log(moduleName, "模块更新写入，请测试")
    } catch (err) {
        console.log(moduleName, "更新失败")
        delete configs[moduleName]
        console.log(err)
    }
}

function getUrl(moduleName, capture) {
    if (!capture) return undefined
    return path.join('/', moduleName, capture).replace(/\\/g, "/")
}

//删除模块
function removeModule(src, moduleName) {
    try {
        let configs = require(configPath);
        delete configs[moduleName]
        fs.writeFileSync(configPath, JSON.stringify(configs, null, "\t"))
    } catch (e) {

    }
}

module.exports = function setConfigApp() {
    chokidar.watch(['public/!(*-bak)/index.json'], {
        persistent: true
    }).on('all', (event, src) => {//监听除了ready, raw, and error之外所有的事件类型

        let pathArr = src.split(path.sep)
        const moduleName = pathArr[pathArr.length - 2]
        if (event == 'unlink') {
            removeModule(src, moduleName)
        } else {
            fileUpdate(src, moduleName)
        }
    });
}